<script setup lang="ts">
import Konva from 'konva'
import { promiseTimeout, useStorage } from '@vueuse/core'
import CommonKonva from '@/components/CommonKonva'
import mapUrl from '@/assets/maps/map.svg'
import agvOff from '@/assets/icons/agv-off.svg'
import { onMounted, ref, watch } from 'vue'
import { mapInfoGroup as mapInfo375, getPointXY as getPointXY375 } from '@/utils/map'
import { mapInfoGroup as mapInfo815, getPointXY as getPointXY815 } from '@/utils/map815'

const loc = import.meta.env.VITE_LOC

const mapInfo = loc === '375' ? mapInfo375 : mapInfo815

const getPointXY = loc === '375' ? getPointXY375 : getPointXY815

const konva = ref()

let group: Konva.Group

const agvStatus = useStorage<any[]>('agv-status', [])

const drawAgvIcon = () => {
  agvStatus.value.map((item) => {
    const { x, y } = getPointXY(item.position, item.id) || { x: -100, y: -100 }
    const agvGroup = new Konva.Group({ name: 'agvCar' + item.id, x, y })
    Konva.Image.fromURL(agvOff, (image) => {
      image.setAttrs({ width: 70, height: 70, offset: { x: 35, y: 35 } })
      agvGroup.add(image)
      const markText = new Konva.Text({
        text: item.id,
        // text: item.id === 1 ? 'A' : 'B',
        fill: '#000',
        stroke: '#000',
        fontSize: 18,
        strokeWidth: 1,
        fontWeight: 'bold',
      })
      markText.offset({ x: 5.5, y: 6 })
      agvGroup.add(markText)
    })
    group.add(agvGroup)
  })
}

const changeAgvIcon = async (agvID, newVal, oldVal) => {
  if (newVal && oldVal) {
    if (!oldVal) return
    const { x: newX, y: newY } = getPointXY(newVal, agvID) || {
      x: null,
      y: null,
    }
    const { x: oldX, y: oldY } = getPointXY(oldVal, agvID) || {
      x: null,
      y: null,
    }
    if (newX === null || newY === null || oldX === null || oldY === null) return
    for (let i = 0; i < 1000; i++) {
      const agvCar = group.findOne('.agvCar' + agvID)
      agvCar.position({
        x: agvCar.x() + (newX - oldX) / 1000,
        y: agvCar.y() + (newY - oldY) / 1000,
      })
      await promiseTimeout(0.1)
    }
  }
}

watch(
  () => agvStatus.value[0]?.position,
  (newVal, oldVal) => changeAgvIcon(1, newVal, oldVal),
)

watch(
  () => agvStatus.value[1]?.position,
  (newVal, oldVal) => changeAgvIcon(2, newVal, oldVal),
)

const doorStatus = useStorage<any[]>('door-status', [])

watch(doorStatus, () => {
  const colorMap = {
    0: '#434343',
    1: '#0AAE8C',
    2: '#f7b22b',
  }
  doorStatus.value.map(({ id, status }) => {
    group.findOne('.door' + id)?.setAttr('fill', colorMap[status])
  })
})

const svgPathData =
  'M192.14853 0.244014h639.514453a58.751808 58.751808 0 0 1 63.869562 60.184779v842.996325a58.751808 58.751808 0 0 1-63.869562 60.184779H192.14853a58.751808 58.751808 0 0 1-64.074271-60.184779V60.428793A58.751808 58.751808 0 0 1 192.14853 0.244014z m63.869562 120.369558v782.811546h511.77533V120.613572zM128.074259 903.425118h767.458286a60.389489 60.389489 0 1 1 0 120.369558H128.074259a60.389489 60.389489 0 1 1 0-120.369558z m281.476432-325.07969a26.612317 26.612317 0 0 1-25.588767-24.155796v-48.106881a26.612317 26.612317 0 0 1 25.588767-24.155795h89.458328a26.612317 26.612317 0 0 1 25.588766 24.155795 22.722825 22.722825 0 0 1-25.588766 23.951086h-63.869562v24.155795a26.817027 26.817027 0 0 1-25.588766 24.155796z'

const drawDoorPoint = () => {
  const doorData =
    loc === '375'
      ? [
          { id: 255, x: 1290, y: 565 },
          { id: 254, x: 1350, y: 680 },
        ]
      : [
          { id: 255, x: 700, y: 400 },
          { id: 254, x: 9999, y: 9999 },
        ]
  const createDoorImage = (id, x, y) => {
    const rect = new Konva.Rect({
      name: `door${id}`,
      x,
      y,
      offset: { x: 20, y: 20 },
      cornerRadius: 5,
      width: 40,
      height: 40,
    })
    const path = new Konva.Path({
      data: svgPathData,
      fill: 'white',
      stroke: 'black',
      strokeWidth: 2,
      scaleX: 0.025,
      scaleY: 0.025,
      x,
      y,
      offset: { x: 500, y: 500 },
    })
    group.add(rect).add(path)
  }
  doorData.forEach(({ id, x, y }) => {
    createDoorImage(id, x, y)
  })
  const colorMap = {
    0: '#434343',
    1: '#0AAE8C',
    2: '#f7b22b',
  }
  doorStatus.value.map(({ id, status }) => {
    group.findOne('.door' + id)?.setAttr('fill', colorMap[status])
  })
}

onMounted(async () => {
  const { layer, group: _group } = await konva.value.onMount()
  group = _group
  group.add(mapInfo)
  drawDoorPoint()
  layer.on('contextmenu', ({ evt }) => evt.preventDefault())
  layer.on('click', function () {
    const { x, y } = layer.getRelativePointerPosition()
    console.log(`x: ${+x.toFixed(2)}, y: ${+y.toFixed(2)}`)
  })
  drawAgvIcon()
})
</script>

<template>
  <CommonKonva ref="konva" container-name="SceenKonva" :img-url="mapUrl"></CommonKonva>
</template>
